<?php

namespace fast;

use Linqiao\Addtran\IpRegion;

/**
 * IP操作类
 * */
class Ip
{

    /**
     * ip地址转换整数
     * */
    public static function ipToInt($ip)
    {
        return sprintf('%u', ip2long($ip));
    }

    /**
     * intip转换为真是ip
     * */
    public static function intToIp($int)
    {
        return long2ip(sprintf('%u', $int));
    }

    /**
     * 获取真实ip地址
     * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * */
    public static function getRealIp(int $type = 0)
    {
        $forwarded = request()->header("x-forwarded-for");
        if ($forwarded) {
            $ip = explode(',', $forwarded)[0];
        } else {
            $ip = request()->ip($type);
        }
        return $ip;
    }

    /**
     * ip地址转真实地址
     * @param $ip string|int ip
     * */
    public static function ipToText($ip)
    {
        if (is_int($ip)) {
            $ip = self::intToIp($ip);
        }
        return (new \Linqiao\Addtran\IpRegion)->setIp($ip)->getIpAddress();
    }

}